package io.xccit.train.common.handler;

import io.xccit.train.common.enums.ResultCode;
import io.xccit.train.common.exception.BusinessException;
import io.xccit.train.common.result.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author CH_ywx
 * @version 1.0
 * @create 2024/11/6
 * <p>全局异常处理</p>
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
        LOGGER.info("全局异常捕获:{}", e.getMessage());
        return AjaxResult.error(ResultCode.ERROR);
    }

    @ExceptionHandler(RuntimeException.class)
    public AjaxResult handleRuntimeException(RuntimeException e) {
        LOGGER.info("全局运行时异常捕获:{}", e.getMessage());
        return AjaxResult.error(500, e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public AjaxResult handleBusinessException(BusinessException e) {
        LOGGER.info("全局业务异常捕获:{}", e.getMessage());
        return AjaxResult.error(500, e.getBusinessCode().getDesc());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public AjaxResult handleNullPointerException(DuplicateKeyException e) {
        LOGGER.info("全局重复键异常捕获:{}", e.getMessage());
        return AjaxResult.error(500, "对象主键重复 请联系管理员");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        LOGGER.info("全局参数校验异常捕获:{}", e.getMessage());
        AjaxResult result = new AjaxResult();
        result.setCode(500);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuffer buffer = new StringBuffer();
        for (ObjectError allError : allErrors) {
            buffer.append(allError.getDefaultMessage()).append(",");
        }
        String message = buffer.toString().substring(0, buffer.length()-1);
        result.setMessage(message);
        return result;
    }
}
